<?php

namespace xing\toutiao;

use xing\helper\resource\HttpHelper;

/**
 * @property $cache
 * @property string $appId
 * @property string $secret;
 */
class BaseService
{
    private $domain = 'https://developer.toutiao.com/';

    public $cache;
    public $appId;
    public $secret;

    public static function init($appId, $secret)
    {
        $class = new static;
        $class->appId = $appId;
        $class->secret = $secret;
        return $class;
    }

    public function setCacheDrive($drive)
    {
        $this->cache = $drive;
        return $this;
    }

    public function getAccessToken()
    {
        $cacheKey = 'TouTiaoAccessToken';
        if (!empty($this->cache)) {
            $accessToken = $this->cache->get($cacheKey);
            if (!empty($accessToken)) return $accessToken;
        }
        $params = ['appid='. $this->appId, 'secret=' . $this->secret, 'grant_type=client_credential'];
        $result = HttpHelper::post($this->domain . 'api/apps/token?' . implode('&', $params));
        if (!isset($result->access_token)) throw new \Exception('请示accessToken失败, 返回值:' . json_encode($result));
        if (!empty($this->cache)) $this->cache->set($cacheKey, $result->access_token, 3600);
        return $result->access_token;
    }

    /**
     * 检查图片是否为合法的
     * @param $url
     * @return bool
     * @throws \Exception
     */
    public function checkImageRight($url)
    {
        $post = ['appid' => $this->appId, 'access_token' => $this->getAccessToken(), 'image' => $url];
        $result = HttpHelper::post($this->domain . 'api/apps/censor/image', $post);
        $isRight = true;
        foreach ($result['predicts'] as $predict) {
            if ($predict['hit']) {
                $isRight = false;
                break;
            }
        }
        return $isRight;
    }
}